package com.newsee.remote.supplier.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.newsee.remote.common.database.entity.CrmPurveycompany;
import com.newsee.remote.common.database.entity.CrmPurveycompanylinkman;
import com.newsee.remote.common.database.mapper.CrmPurveycompanyMapper;
import com.newsee.remote.common.dto.supplier.SupplierDTO;
import com.newsee.remote.common.dto.supplier.srm.*;
import com.newsee.remote.common.enumeration.SrmRspStatusCodeEnum;
import com.newsee.remote.common.utils.ecache.ConcurrentHashMapCacheUtil;
import com.newsee.remote.common.utils.tools.DateUtils;
import com.newsee.remote.common.vo.supplier.*;
import com.newsee.remote.supplier.service.ICrmPurveycompanyService;
import com.newsee.remote.supplier.service.ICrmPurveycompanylinkmanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author liangzhichen
 * @since 2019-07-31
 */
@Slf4j
@Service
public class CrmPurveycompanyServiceImpl extends ServiceImpl<CrmPurveycompanyMapper, CrmPurveycompany> implements ICrmPurveycompanyService {

    private final ICrmPurveycompanylinkmanService iCrmPurveycompanylinkmanService;

    public CrmPurveycompanyServiceImpl(ICrmPurveycompanylinkmanService iCrmPurveycompanylinkmanService) {
        this.iCrmPurveycompanylinkmanService = iCrmPurveycompanylinkmanService;
    }

    @Override
    public SrmVO acceptSupplier(SrmDTO srmDTO) {
        SrmVO srmVO = new SrmVO();

        if (!checkData(srmDTO)) {
            generatorRspBaseInfo(srmDTO, srmVO, SrmRspStatusCodeEnum.SEND_MESSAGE_ERROR.getCode());
            return srmVO;
        }

        try {
            //srm提供的供应商报文
            HeadDTO supplier = srmDTO.getI_REQUEST().getMESSAGE().getREQ_ITEM().getHEAD();

            //封装请求
            SupplierDTO supplierDTO = new SupplierDTO();

            //("SRM供应商唯一标识")
            String guid = supplier.getLIFNR_GUID();
            boolean lock = ConcurrentHashMapCacheUtil.lock(guid);
            if (!lock){
                generatorRspBaseInfo(srmDTO, srmVO, SrmRspStatusCodeEnum.SEND_MESSAGE_ERROR.getCode());
                return srmVO;
            }
            QueryWrapper<CrmPurveycompany> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("GUID", guid);
            CrmPurveycompany crmPurveycompany = getOne(queryWrapper);

            //新增
            if (null == crmPurveycompany) {
                crmPurveycompany = new CrmPurveycompany();
                crmPurveycompany.setCreateDate(LocalDateTime.now());
                crmPurveycompany.setCreateTime(LocalDateTime.now());
                crmPurveycompany.setCheckUserName("供应商增量同步");
                supplierDTO.setGuid(guid);
            } else {
                //删除
                if ("1".equals(supplier.getDELETE_FALG())) {
                    remove(queryWrapper);
                    generatorRspBaseInfo(srmDTO, srmVO, SrmRspStatusCodeEnum.HANDLE_SUCCESS.getCode());
                    return srmVO;
                }
            }
            crmPurveycompany.setUpdateDate(LocalDateTime.now());

            //属性转换
            transformData(supplierDTO, supplier);
            BeanUtils.copyProperties(supplierDTO, crmPurveycompany);
            crmPurveycompany.setTaxRegister(supplierDTO.getTaxId());
            crmPurveycompany.setSourceType(1);
            crmPurveycompany.setGroupID(13);
            crmPurveycompany.setCompanyType("6");
            //服务范围
            List<ItemScopDTO> scopes = supplier.getITEM_SCOPE();
            if (CollectionUtils.isNotEmpty(scopes)) {
                StringBuilder serviceRange = new StringBuilder();
                for (ItemScopDTO scope : scopes) {
                    serviceRange.append(",").append(scope.getSCOPE_DESC());
                }
                crmPurveycompany.setSRMServiceRange(serviceRange.substring(1));
            }
            saveOrUpdate(crmPurveycompany);

            //--------------------联系信息(多个)-----------------
            List<ItemPersonDTO> persons = supplier.getITEM_PERSON();
            if (CollectionUtils.isNotEmpty(persons)) {
                //先删除，后新增
                QueryWrapper<CrmPurveycompanylinkman> queryWrapperLinkMan = new QueryWrapper<>();
                queryWrapperLinkMan.eq("PurveyID", crmPurveycompany.getId());
                iCrmPurveycompanylinkmanService.remove(queryWrapperLinkMan);
                for (ItemPersonDTO person : persons) {
                    CrmPurveycompanylinkman linkman = new CrmPurveycompanylinkman();
                    linkman.setMobilePhone(person.getMOBILE_PHONE());
                    linkman.setLinkmanName(person.getCONTACT_NAME());
                    linkman.setMail(person.getEMAIL());
                    linkman.setPurveyID(crmPurveycompany.getId());
                    linkman.setCreateDate(LocalDateTime.now());
                    linkman.setUpdateUserName("供应商增量同步");
                    linkman.setGuid(crmPurveycompany.getGuid());
                    iCrmPurveycompanylinkmanService.save(linkman);
                }
            }
            ConcurrentHashMapCacheUtil.unLock(guid);
            generatorRspBaseInfo(srmDTO, srmVO, SrmRspStatusCodeEnum.HANDLE_SUCCESS.getCode());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("供应商同步出错：" + e.getMessage());
            generatorRspBaseInfo(srmDTO, srmVO, SrmRspStatusCodeEnum.INTERNAL_ERROR.getCode());
            return srmVO;
        }
        return srmVO;
    }

    @Override
    public CrmPurveycompany findByLifnr(String lifnr) {
        QueryWrapper<CrmPurveycompany> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("Lifnr", lifnr);
        return getOne(queryWrapper);
    }

    /**
     * @param srmDTO 请求报文
     */
    private Boolean checkData(SrmDTO srmDTO) {
        //默认成功
        Boolean flag = true;
        return true;
    }


    /**
     * srm 对应属性名转换
     *
     * @param supplierDTO 目标源
     * @param supplier    srm数据
     */
    private void transformData(SupplierDTO supplierDTO, HeadDTO supplier) {
        //供应商编码
        String lifnr = supplier.getLIFNR();
        if (null != lifnr) {
            supplierDTO.setLifnr(lifnr);
        }

        //("供应商名称")
        String companyName = supplier.getLIFNR_NAME();
        if (null != companyName) {
            supplierDTO.setCompanyName(companyName);
        }

        //("供应商简称")
        String simpleName = supplier.getLIFNR_NAME1();
        if (null != simpleName) {
            supplierDTO.setSimpleName(simpleName);
        }

        //("传真")
        String fax = supplier.getTELEFAX();
        if (null != fax) {
            supplierDTO.setFax(fax);
        }


        //("邮编")
        String postalcode = supplier.getZIP_CODE();
        if (null != postalcode) {
            supplierDTO.setPostalcode(postalcode);
        }

        //--------------------结算信息-----------------
        List<ItemBankDTO> banks = supplier.getITEM_BANK();

        if (CollectionUtils.isNotEmpty(banks)) {
            ItemBankDTO bank = banks.get(0);
            //("开户银行")
            supplierDTO.setOpenBank(bank.getBANK_NAME());


            //("开户银行")
            String bankAccount = bank.getTAX_REG_NO();
            if (null != bankAccount) {
                supplierDTO.setBankAccount(bankAccount);
            }

        }

        //纳税人识别号
        String taxId = supplier.getBUS_LICENCE();
        if (null != taxId) {
            supplierDTO.setTaxId(taxId);
        }

    }

    /**
     * 生成响应报文基础信息名称
     *
     * @param srmDTO 请求
     * @param srmVO  返回
     */
    private void generatorRspBaseInfo(SrmDTO srmDTO, SrmVO srmVO, String rspStatsCode) {
        //请求报文根节点
        IRequestDTO iRequest = srmDTO.getI_REQUEST();
        //请求报文基本信息
        RspBaseInfoDTO reqBaseinfo = iRequest.getREQ_BASEINFO();


        //-------封装返回对象--------
        //响应报文根节点名称
        EResponseVO eResponseVO = new EResponseVO();
        srmVO.setE_RESPONSE(eResponseVO);

        //响应报文基础信息名称
        RspBaseInfoVO rspBaseInfoVO = new RspBaseInfoVO();
        eResponseVO.setRSP_BASEINFO(rspBaseInfoVO);
        //接收系统返回消息，产生的 TRACE_ID，消息的唯一标识
        rspBaseInfoVO.setRSP_TRACE_ID(UUID.randomUUID().toString().replace("-", ""));
        //响应请求 TRACE_ID
        rspBaseInfoVO.setRSP_REQ_TRACEID(reqBaseinfo.getREQ_TRACE_ID());
        //报文发送时间，14位数字
        rspBaseInfoVO.setRSP_SEND_TIME(Long.valueOf(DateUtils.format(new Date(), DateUtils.DATE_PATTERN_FULL)));
        //发送方系统标识
        rspBaseInfoVO.setRSP_SRC_SYS(reqBaseinfo.getREQ_SRC_SYS());
        //接收方系统标识:
        rspBaseInfoVO.setRSP_TAR_SYS("BS-WY-RFWZ");
        //PO 或 ESB 上定义的SI名称，由PO或ESB/顾问提供
        rspBaseInfoVO.setRSP_SERVER_NAME(reqBaseinfo.getREQ_SERVER_NAME());
        //业务系统流水号或业务唯一编号，从请求报文中获取
        rspBaseInfoVO.setRSP_BSN_ID(reqBaseinfo.getREQ_BSN_ID());
        //接口处理状态代码
        rspBaseInfoVO.setRSP_STATUS_CODE(rspStatsCode);

        //给srm返回的信息
        MessageVO messageVO = new MessageVO();
        RspItemVO rspItemVO = new RspItemVO();
        eResponseVO.setMESSAGE(messageVO);
        messageVO.setRSP_ITEM(rspItemVO);
        rspItemVO.setRSP_STATUS_CODE(rspStatsCode);
        rspItemVO.setRSP_STATUS_MSG(SrmRspStatusCodeEnum.getTextByCode(rspStatsCode));
    }

}
